<?php


namespace King\Service;


use King\Entity\Poker\Poker;
use King\Entity\Poker\Room;
use King\Entity\User\User;

class PokerRoomService
{

    /** @var Room */
    public $room;

    public function make(User $user): PokerRoomService
    {
        $this->room = new Room();
        $this->room->id = uniqid('poker');
        $this->room->name = $this->room->id;
        $this->room->totalNumber = 3;
        $this->room->onlineNumber = 0;
        $this->room->addUser($user);
        return $this;
    }

    public function join(User $user)
    {
        $this->room->addUser($user);
    }

    public function start(): PokerRoomService
    {
        $list = (new PokerService)->deal();
        /** @var User $item */
        foreach ($this->room->userList as $index => $item) {
            $cardList = $list['person'][$item->seat - 1];
            /** @var Poker $mainCard */
            $mainCard = $list['mainCard'];
            /** @var Poker $cardObj */
            foreach ($cardList as $cardObj) {
                if ($cardObj->name == $mainCard->name && $cardObj->color == $mainCard->color) {
                    $this->room->userList[$index]->banker = true;
                    $cardList = array_merge($cardList, $list['hand']);
                }
            }
            $this->room->userList[$index]->cardList = $cardList;
        }
        return $this;
    }

    public function play(User $user): PokerPlayService
    {
        return new PokerPlayService($user);
    }
}